<template>
  <view class="pdf-scroll-container">
    <!-- 顶部标题栏 -->
    <view class="pdf-header">
      <view class="header-title">{{currentTemplate.name}}</view>
      <view class="page-indicator">
        第 {{currentPage}} / {{pdfPages.length}} 页
      </view>
    </view>
    
    <!-- PDF页面滚动区域 -->
    <scroll-view 
      class="pdf-scroll-view" 
      scroll-y 
      :scroll-top="scrollTop"
      @scroll="handleScroll"
    >
      <view class="pdf-page-container">
        <view 
          class="pdf-page-item" 
          v-for="(page, index) in pdfPages" 
          :key="index"
          :id="'page-' + (index + 1)"
        >
          <image 
            class="pdf-page-image" 
            :src="page.imgUrl" 
            mode="widthFix"
            @load="onImageLoad(index)"
          />
          <view class="page-number">第 {{index + 1}} 页</view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 底部操作按钮 -->
    <view class="pdf-footer">
      <button class="footer-btn use-btn" @click="startSign">
        发起合同签署
      </button>
    </view>
    
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'

// 模拟PDF页面数据
const pdfPages = ref([
  { imgUrl: '/static/contract-page1.jpg', height: 0 },
  { imgUrl: '/static/contract-page2.jpg', height: 0 },
  { imgUrl: '/static/contract-page3.jpg', height: 0 },
  { imgUrl: '/static/contract-page4.jpg', height: 0 }
])

const currentTemplate = ref({
  id: 1,
  name: '红薯山药平台供应链入驻合同'
})

const currentPage = ref(1)
const scrollTop = ref(0)
const pagePositions = ref([])

// 图片加载完成时计算位置
function onImageLoad(index) {
  nextTick(() => {
    const query = uni.createSelectorQuery()
    query.select(`#page-${index + 1}`).boundingClientRect()
    query.exec(res => {
      if (res[0]) {
        pdfPages.value[index].height = res[0].height
        calculatePagePositions()
      }
    })
  })
}

// 计算每页的位置信息
function calculatePagePositions() {
  let positions = []
  let currentPosition = 0
  
  pdfPages.value.forEach((page, index) => {
    positions.push({
      page: index + 1,
      start: currentPosition,
      end: currentPosition + page.height
    })
    currentPosition += page.height
  })
  
  pagePositions.value = positions
  console.log('页面位置信息:', positions)
}

// 滚动事件处理 - 优化版本
function handleScroll(e) {
  const scrollTop = e.detail.scrollTop
  const windowHeight = uni.getSystemInfoSync().windowHeight
  const viewportCenter = scrollTop + windowHeight / 2
  
  let visiblePage = 1
  
  for (let i = 0; i < pagePositions.value.length; i++) {
    const pos = pagePositions.value[i]
    if (viewportCenter >= pos.start && viewportCenter <= pos.end) {
      visiblePage = pos.page
      break
    }
  }
  
  if (visiblePage !== currentPage.value) {
    currentPage.value = visiblePage
    console.log('页码更新为:', currentPage.value, '滚动位置:', scrollTop)
  }
}

// 跳转到指定页
function goToPage(pageNum) {
  if (pageNum < 1 || pageNum > pdfPages.value.length) return
  
  const position = pagePositions.value[pageNum - 1].start
  scrollTop.value = position
  currentPage.value = pageNum
  
  // 由于scroll-top需要变化才能触发滚动，这里强制更新
  scrollTop.value = position + 1
}

// 分享模板按钮点击事件
function handleShare() {
  // 这个函数现在不会被调用，因为使用了 open-type="share"
  // 但保留它以防需要其他分享逻辑
  console.log('分享按钮被点击')
}


// 微信小程序分享给好友 - 这是微信小程序的原生分享方法
function onShareAppMessage() {
  return {
    title: currentTemplate.value.name,
    desc: '这是一个优质的合同模板，快来使用吧！',
    path: '/pages/template/index?id=' + currentTemplate.value.id,
    imageUrl: '/static/logo.png'
  }
}

// 微信小程序分享到朋友圈
function onShareTimeline() {
  return {
    title: currentTemplate.value.name,
    desc: '这是一个优质的合同模板，快来使用吧！',
    path: '/pages/template/index?id=' + currentTemplate.value.id,
    imageUrl: '/static/logo.png'
  }
}

// 使用模板
function handleUseTemplate() {
  uni.showModal({
    title: '使用模板',
    content: `确定使用"${currentTemplate.value.name}"模板吗？`,
    success: (res) => {
      if (res.confirm) {
        uni.navigateTo({
          url: `/pages/create/index?id=${currentTemplate.value.id}`
        })
      }
    }
  })
}

function startSign() {
  uni.navigateTo({ url: '/pages/success/index' })
}

onMounted(() => {
  // 初始化页面位置计算
  setTimeout(() => {
    calculatePagePositions()
  }, 1000)
})
</script>

<style scoped>
.pdf-scroll-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

/* 顶部标题栏 */
.pdf-header {
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.page-indicator {
  font-size: 28rpx;
  color: #666;
}

/* PDF滚动区域 */
.pdf-scroll-view {
  flex: 1;
  height: 1px; /* 必须设置高度才能滚动 */
}

.pdf-page-container {
  padding: 20rpx;
}

.pdf-page-item {
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.pdf-page-image {
  width: 100%;
  display: block;
}

.page-number {
  padding: 15rpx;
  text-align: center;
  font-size: 26rpx;
  color: #999;
  border-top: 1rpx solid #eee;
}

/* 底部操作按钮 */
.pdf-footer {
  padding: 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
}

.footer-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: 500;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

.footer-btn::after {
  border: none;
}

.share-btn {
  background-color: #ff9a9e;
}

.use-btn {
  background-color: #ff4757;
}
</style>